!function($) {

	var url, 
	    data, 
	    dropdownMenu, 
	    searchInput,
	    searchType,
	    callback;

	$.fn.autoComplete = function(options) {
		url = options.url;// remote url
		data = options.data;// params
		searchTypeInput = options.searchTypeInput;
		dropdownMenu = options.dropdownMenu;// selector
		searchInput = $(this);

		processDropdownMenu();

	}

	$("body").click(function() {
		$(dropdownMenu).hide();
		curPos = -1;
	})

	var processDropdownMenu = function() {
		$(dropdownMenu).html('');
		$(dropdownMenu).hide();
		var curPos = -1;
		
		searchInput.keyup(event, function() {
			console.log($(searchTypeInput).val());
			if($(searchTypeInput).val() != 3){
				return;
			}
			$(dropdownMenu).show();
			if (event.keyCode == 38) {
				// 向上移动
				var length = $(dropdownMenu).find('li').length;

				if (curPos <= -1) {
					curPos = length - 1;
				} else if (curPos >= 0 && curPos <= length - 1) {
					curPos--;
				}
				$(dropdownMenu).find("li").removeClass("active");
				$(dropdownMenu).find("li:eq(" + curPos + ")")
						.addClass("active");
				return;
			} else if (event.keyCode == 40) {
				// 向下移动
				var length = $(dropdownMenu).find('li').length;
				if (curPos <= -1) {
					curPos = 0;
				} else if (curPos >= 0 && curPos <= length - 2) {
					curPos++;
				} else if (curPos == length - 1) {
					curPos = 0;
				}
				$(dropdownMenu).find("li").removeClass("active");
				$(dropdownMenu).find("li:eq(" + curPos + ")")
						.addClass("active");
				return;
			} else if (event.keyCode == 13) {
				searchInput.val($(dropdownMenu).find(".active a").html());
				$(dropdownMenu).html('');
				$(dropdownMenu).hide();
				curPos = -1;
			}

			curPos = -1;

			var search = searchInput.val();
			
			$.ajax({
				url:url,
				data:{partCode:search},
				dataType:'json',
				success:function(array){
					if(!array || array == null || array == ''){
						$(dropdownMenu).html('');
						return;
					}
					var notmatch = true;
					
					for ( var i in array) {
						if (notmatch) {
							$(dropdownMenu).html('');
						}
						notmatch = false;
						$(dropdownMenu).append(
								'<li class="item"><a tabindex="-1">' + array[i]
										+ '</a></li>');
					}
					notmatch = true;
					
					$(dropdownMenu).find('li.item').click(function() {
						searchInput.val($(this).find("a").html());
						$(dropdownMenu).hide();
						curPos = -1;
					})
				}
			})
			
			

			

		})

	}

}(window.jQuery);